package com.jswitch.server.process.requset;

import com.jswitch.common.exception.SipException;
import com.jswitch.server.cache.TransactionManageCache;
import com.jswitch.server.msg.SipMessageEvent;
import com.jswitch.server.process.AbstractSipMessageProcess;
import com.jswitch.server.transaction.ServerSipTransaction;
import com.jswitch.server.transaction.SipTransactionUser;
import com.jswitch.service.service.ILocationService;
import com.jswitch.sip.*;
import com.jswitch.sip.adress.AddressImpl;
import com.jswitch.sip.header.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Objects;

@Slf4j
@Component("INVITE")
public class InviteSipMessageProcess extends AbstractSipMessageProcess {

    @Resource
    private ILocationService locationService;


    @Override
    public void handleRequest(SipMessageEvent event) {
        SipRequest sipRequest = (SipRequest) event.getMessage();
        ServerSipTransaction serverTransaction = TransactionManageCache.getServerTransaction(event.getMessage().getTransactionId());
        if (checkAuthorization(sipRequest)) {
            SipResponse response = sipRequest.createResponse(SipResponseStatus.RINGING.getStatusCode());
            SipResponse okResponse = sipRequest.createResponse(SipResponseStatus.OK.getStatusCode());
            RecordRouteList recordRouteHeaders = sipRequest.getRecordRouteHeaders();
            if(Objects.nonNull(recordRouteHeaders)){
                response.addHeader(recordRouteHeaders);
                okResponse.addHeader(recordRouteHeaders);
            }

            Contact contact = new Contact();
            GenericURI uri = sipRequest.getRequestLine().getUri();
            AddressImpl address = new AddressImpl();
            address.setAddess(uri);
            contact.setAddress(address);
            response.addHeader(contact);
            okResponse.addHeader(contact);

            serverTransaction.sendResponse(response);

            String contentString = new String(sipRequest.getRawContent());
            //todo 创建一个SDP对象
            SDPMessage sdpMessage = new SDPMessage();
            // 设置SDP
            okResponse.setMessageContent("application","sdp", contentString);
            serverTransaction.sendResponse(okResponse);
            //return response;
        } else {
            serverTransaction.sendResponse(sendUnauthorizedResponse(sipRequest));
        }
    }

}
